<template>
  <div id="note-editor-container">
    <div id="note-editor-header">
        <input class="note-title"
               :disabled="isShareNote && !note.editable"
               :style="{color: note.title === '请输入文章标题' ? 'gray' : 'black' }"
               @focus="note.title = note.title ==='请输入文章标题'?'':note.title"
               @blur="note.title = note.title ===''?'请输入文章标题':note.title"
               v-model="note.title"/>
        <div class="functional-area" v-if="!isShareNote || note.editable">
          <img src="../assets/img/save.png" alt="" title="保存" @click="saveNote()">
          <img src="../assets/img/label.png" alt="" title="添加标签" @click="setTag()">
          <img src="../assets/img/classification.png" alt="" title="选择分类" @click="selectCategory()">
          <img src="../assets/img/encryption.png" alt="" title="加密" @click="dialogPasswordVisible = true">
          <img src="../assets/img/share.png" alt="" title="分享" @click="shareNote()">
        </div>
    </div>
    <div id="note-editor-content">
      <ckeditor class="editor"
                id="editor"
                ref="editor"
                :key="editorKey"
                :editor="editor"
                v-model="editorData"
                :config="editorConfig"
                @focus="editorFocus()"
                @blur="editorData = editorData ===''?'<p>请输入正文</p>':editorData">
      </ckeditor>
    </div>
    <el-dialog title="选择文章类型" :visible.sync="dialogFormVisible" center width="30%" top="25vh">
      <el-form>
        <el-form-item label="选择分类" :label-width="formLabelWidth">
          <el-select v-model="category"  placeholder="请选择文章类型" width="80%">
            <el-option v-for="category in categoryList" :key="category.categoryId" :label="category.name" :value="category" ></el-option>
          </el-select>
          <div class="new-category-box">
            <el-button type="primary" class="new-category" @click="innerVisible = true">新建分类</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="categoryAndNoteSave">保 存</el-button>
      </div>
      <!--      内联 新建分类对话框-->
      <el-dialog
        class="inner-dialog"
        width="30%"
        top="25vh"
        title="新建分类"
        :visible.sync="innerVisible"
        append-to-body
        center>
        <el-form>
          <el-form-item label="分类名称" :label-width="formLabelWidth">
            <el-input placeholder="请输入分类名称" v-model="category.name"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="innerVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveCategory">保 存</el-button>
        </div>
      </el-dialog>
    </el-dialog>

<!--    输入标签弹窗-->
    <el-dialog title="输入笔记标签" :visible.sync="dialogTabVisible" center width="30%" top="25vh">
      <el-form>
        <el-form-item label="输入标签" :label-width="formLabelWidth">
          <el-input  v-model="note.tag" @focus="insertTag"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTabVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveTag">保 存</el-button>
      </div>
    </el-dialog>

    <!--    输入密码弹窗-->
    <el-dialog title="输入密码" :visible.sync="dialogPasswordVisible" center width="30%" top="25vh">
      <el-form>
        <el-form-item v-if="note.password" label="旧密码" :label-width="formLabelWidth">
          <el-input  v-model="oldPassword"></el-input>
        </el-form-item>
        <el-form-item label="新密码" :label-width="formLabelWidth">
          <el-input  type="password"  v-model="newPassword"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTabVisible = false">取 消</el-button>
        <el-button type="primary" @click="savePassword">保 存</el-button>
      </div>
    </el-dialog>

<!--    分享设置页面-->
    <el-dialog title="分享文章" :visible.sync="dialogShareVisible" center width="30%" top="25vh">
      <el-form>
        <!--        <el-form-item label="活动名称" :label-width="formLabelWidth">-->
        <!--          <el-input v-model="form.name" autocomplete="off"></el-input>-->
        <!--        </el-form-item>-->
        <el-form-item label="分享链接" class="share-box">
          <el-input
            placeholder="请输入内容"
            v-model="shareNoteLink"
            readonly>
          </el-input>
          <el-button @click="copyShareNoteLink()">复制链接</el-button>
        </el-form-item>
        <el-form-item label="是否可编辑" :label-width="formLabelWidth">
          <el-radio v-model="note.editable" label="1" >允许编辑</el-radio>
          <el-radio v-model="note.editable" label="0">仅可查看</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTabVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveNote()">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入node_modules中的ckeditor5开始
import {ClassicEditor} from '@ckeditor/ckeditor5-editor-classic';

import { Alignment } from '@ckeditor/ckeditor5-alignment';  // Importing the package.
import { Autoformat } from '@ckeditor/ckeditor5-autoformat';
import { Bold, Italic } from '@ckeditor/ckeditor5-basic-styles';
import { BlockQuote } from '@ckeditor/ckeditor5-block-quote';
import { CloudServices } from '@ckeditor/ckeditor5-cloud-services';
import { Essentials } from '@ckeditor/ckeditor5-essentials';
import { Heading } from '@ckeditor/ckeditor5-heading';
import {
  Image,
  ImageCaption,
  ImageStyle,
  ImageTextAlternative,
  ImageToolbar,
  ImageUpload
} from '@ckeditor/ckeditor5-image';

import { Indent } from '@ckeditor/ckeditor5-indent';
import { Link } from '@ckeditor/ckeditor5-link';
import { List } from '@ckeditor/ckeditor5-list';
import { MediaEmbed } from '@ckeditor/ckeditor5-media-embed';
import { Paragraph } from '@ckeditor/ckeditor5-paragraph';
import { PasteFromOffice } from '@ckeditor/ckeditor5-paste-from-office';
import { Table, TableToolbar } from '@ckeditor/ckeditor5-table';
import { TextTransformation } from '@ckeditor/ckeditor5-typing';
import UrlParam from '@/utils/getUrlParam';

// 引入node_modules中的ckeditor5结束

// import Editor from 'ckeditor5-custom-build/build/ckeditor';//引入自定义的ckeditor5

//引入工具包
export default {
  name: 'NoteEditor',
  // components:{
  //   ckeditor: CKEditor.component
  // },
  data() {
    return {
      editor: ClassicEditor,
      editorData: '<p>请输入正文</p>',
      editorConfig: { //node_modules中的ckeditor5
        language: 'zh-cn', // 设置语言为中文
        isReadOnly: this.readOnly, // 设置为只读模式
        // extraPlugins:[this.createUploadAdapterPlugin],
        plugins: [
          Alignment,  // Adding the package to the list of plugins.
          Autoformat,
          BlockQuote,
          Bold,
          CloudServices,
          Essentials,
          Heading,
          Image,
          ImageCaption,
          ImageStyle,
          ImageToolbar,
          ImageUpload,
          ImageTextAlternative,
          Indent,
          Italic,
          Link,
          List,
          MediaEmbed,
          Paragraph,
          PasteFromOffice,
          Table,
          TableToolbar,
          TextTransformation
        ],
        toolbar: {
          items: [
            'alignment',  // Displaying the proper UI element in the toolbar.
            'heading',
            '|',
            'bold',
            'italic',
            'link',
            'bulletedList',
            'numberedList',
            'imageUpload',
            '|',
            'outdent',
            'indent',
            '|',
            'imageUpload',
            'blockQuote',
            'insertTable',
            'mediaEmbed',
            'undo',
            'redo'
          ]
        },
      },
      note:{
        title:"请输入文章标题",
        categoryName: '',
        categoryId: 0,
        password:'',
        tag: '',
        content: '<p>请输入正文</p>',
        editable:1,
      },
      image: {
        toolbar: [
          'imageTextAlternative',
          '|',
          'imageStyle:alignLeft',
          'imageStyle:full',
          'imageStyle:alignRight'
        ],
        styles: [
          'full',
          'alignLeft',
          'alignRight'
        ],
        upload: {
          types: ['jpeg', 'png', 'gif', 'bmp', 'webp', 'tiff'],
          url: 'http://localhost:8090/imageUpload/upload-endpoint'
        }
      },
      oldPassword:'',
      newPassword:'',
      category: {

      },
      readOnly:true,
      isShareNote:false,
      shareNoteLink:'',
      categoryList: [],
      dialogFormVisible: false,
      dialogTabVisible: false,
      dialogPasswordVisible:false,
      dialogShareVisible:false,
      innerVisible: false,
      formLabelWidth: '120px',
      editorKey:'0',


    }
  },
  methods: {
    createUploadAdapterPlugin(editor) {
      editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
        return {
          upload: function() {
            return new Promise((resolve, reject) => {
              const data = new FormData();
              data.append('upload', loader.file);
              this.$request.post('http://localhost:8090/imageUpload/upload-endpoint', data)
                .then(res => {
                  if (res.data.url) {
                    resolve({ default: res.data.url });
                  } else {
                    reject('Upload failed');
                  }
                })
                .catch(reject);
            });
          },
          abort: function() {
            // 在这里处理上传中断的逻辑。
          }
        };
      };
      return editor;
    },
    setEditorReadOnly() {
      document.querySelector('.ck-toolbar').style.display = 'none';
      document.querySelector('.ck-content').setAttribute('contenteditable', false);
    },
    setEditorEditable() {
      document.querySelector('.ck-toolbar').style.display = 'block';
      document.querySelector('.ck-content').setAttribute('contenteditable', true);
    },
    // 复制分享链接
    async copyShareNoteLink() {
      try {
        await navigator.clipboard.writeText(this.shareNoteLink);
        this.$messageHelper.messageSuccess('复制成功');
      } catch (err) {
        console.error('复制链接失败: ', err);
      }
    },
    //配置分享
    shareNote(){
      if(this.note?.noteId === undefined || this.note?.noteId === null || this.note?.noteId === 0){
        return this.$messageHelper.messageWarning('请先保存笔记');
      }
      this.shareNoteLink = window.location.href + '/shareNoteId=' + this.note.noteId;
      this.dialogShareVisible = true;
    },

    // 设置笔记
    setNote(noteId){
      let nid = noteId ? noteId : this.$currentNote.noteId;
      this.$request.get('/category/getInfo/' + nid).then(res => {
        if(res.data.code === 200){
          this.note.categoryName = res.data.data?.name;
        }else{
          this.$messageHelper.messageWarning(res.data.msg);
        }
      })
    },

    // 保存密码
    savePassword(){
        if(!this.newPassword) return this.$messageHelper.messageWarning('请输入密码');
        this.$request.post('/note/updatePassword', {'note_id':this.note.noteId,'new_password':this.newPassword,'old_password':this.oldPassword}).then(res => {
          if(res.data.code === 200){
            this.setNote(this.note.noteId);
            this.$messageHelper.messageSuccess('保存成功');
            this.oldPassword = '';
            this.dialogPasswordVisible = false;
          }else{
            this.$messageHelper.messageWarning(res.data.msg);
          }
        })
    },
    // 设置标签开始
    // 保存标签 标签弹窗点击保存触发
    saveTag(){
      if(this.$currentNote.hasOwnProperty('noteId')){
        this.note.tag = this.note.tag.replace('#','');
        this.$currentNote.tag = this.note.tag;
        this.$request.put('/note/update',this.note).then(res => {
          if(res.data.code === 200){
            this.$messageHelper.messageSuccess('保存成功');
          }else{
            this.$messageHelper.messageWarning(res.data.msg);
          }
        })
      }
      this.dialogTabVisible = false;
    },
    // 插入标签 标签输入框获取焦点触发
    insertTag(){
      if(!this.note.tag.endsWith('#')){
        this.note.tag = this.note.tag + ' #';
      }
      this.dialogTabVisible = true;
    },
    // 设置标签 标签图标点击触发
    setTag(){
      if(this.$currentNote.hasOwnProperty('tag')){
        this.note.tag = this.$currentNote.tag;
      }
      this.dialogTabVisible = true;
    },
    // 设置标签结束

    // 保存笔记开始

    // 监听ctrl+s保存笔记
    keydownSaveNote(event){
      if (event.ctrlKey && event.key.toLowerCase() === 's') {
        event.preventDefault(); // 阻止浏览器默认的保存操作
        this.saveNote();
      }
    },
    // 保存分类同时保存笔记 标签弹窗点击保存触发
    categoryAndNoteSave(){
      this.$currentNote.categoryId = this.note.categoryId;
      this.saveNote();
    },
    // 获取分类列表 弹窗打开时触发
    async dialogCategoryList(){
      this.$request.get('/category/list').then(res => {
        if(res.data.code === 200){
          res.data.data ? this.categoryList = res.data.data.categoryList.list : [];
        }else{
          this.$messageHelper.messageWarning(res.data.msg);
        }
      })
    },
    // 保存分类 内联分类弹窗点击保存触发
    async saveCategory(){
      if(this.note.categoryName === ''){
        return this.$messageHelper.messageWarning('请输入分类名称');
      }
      this.$request.post('/category/save',{'name':this.category.name}).then(async res => {
        if (res.data.code === 200) {
          this.category = res.data.data;
          this.note.categoryId = this.category.categoryId;
          this.note.categoryName = this.category.name;
          this.$messageHelper.messageSuccess('保存成功');
          await this.dialogCategoryList();
          this.innerVisible = false;
        } else {
          this.$messageHelper.messageWarning(res.data.msg);
        }
      })
    },
    selectCategory(){
      this.dialogCategoryList();
      this.dialogFormVisible = true;
    },
    // 保存笔记 标题输入框失去焦点触发
    async saveNote(){
      if(sessionStorage.getItem('user') === null){
        this.$messageHelper.messageWarning('请先登录');
        return this.$router.push('/');
      }
      if(this.note.title === '请输入文章标题' || this.note.title === ''){
        return this.$messageHelper.messageWarning('请输入文章标题');
      }
      if(this.note.content === '<p>请输入正文</p>' ||this.note.content === ''){
        return this.$messageHelper.messageWarning('请输入正文');
      }
      if(! this.note.hasOwnProperty('categoryId') ||  this.note.categoryId === 0 || this.note.categoryId === null || this.$currentNote.categoryId === undefined){
        this.selectCategory();
        return
      }
      await this.$request.post('/note/save', this.note).then(res => {
        console.log(res.data,1111)
        if(res.data.code === 200){
          this.dialogShareVisible = false;
          this.$messageHelper.messageSuccess('保存成功');
        }else{
          this.$messageHelper.messageWarning(res.data.msg);
        }
      })
    },
    // 保存笔记结束

    editorFocus(){
      this.editorData === '<p>请输入正文</p>' ? this.editorData = '' : this.editorData;
    }
  },
  watch:{
    editorData(val){
      this.note.content = val;
      this.$currentNote.content = val;
    },
    category(val){
      console.log(val,1111)
      this.note.categoryId = val.categoryId;
      this.note.categoryName = val.name;
    },
    // 'note.categoryId'(val){
    //   this.$request.get('/category/getInfo/' + val).then(res => {
    //     if(res.data.code === 200){
    //        this.note.categoryName = res.data.data?.name;
    //     }else{
    //       this.$messageHelper.messageWarning(res.data.msg);
    //     }
    //   })
    // },
  },
  mounted() {
    // 从sessionStorage中获取用户信息
    let user = JSON.parse(sessionStorage.getItem('user') ? sessionStorage.getItem('user'):"{}");
    let shareNoteId = this.$route.query?.shareNoteId;
    //不是分享 也没有登录的情况下跳转到登录页面
    console.log('this.$route.query?.shareNoteId',shareNoteId)
    // shareNoteId || user?.userId ||  this.$router.push('/');
    if(shareNoteId){
      this.$request.get('/note/getInfo/'+shareNoteId).then(res => {
        if(res.data.code === 200){
          this.isShareNote = true;
          this.note = this.$currentNote = res.data.data;
          this.note.editable ? this.setEditorEditable() : this.setEditorReadOnly();
        }else{
          this.$messageHelper.messageWarning(res.data.msg);
        }
      })
    }
    if(this.$currentNote?.noteId){
      this.$request.get('/note/getInfo/'+this.$currentNote?.noteId).then(res => {
        if(res.data.code === 200){
          this.editorData = res.data.data.content;
          res.data.data ? this.note = this.$currentNote = res.data.data : '' ;
        }else{
          this.$messageHelper.messageWarning(res.data.msg);
        }
      })
    }else if(this.$previousRoute?.path === '/' && !shareNoteId){
      this.$request.get('/note/getCurrentNote/'+user?.userId).then(res => {
        if(res.data.code === 200){
          res.data.data ? this.note = this.$currentNote = res.data.data : '' ;
        }else{
          this.$messageHelper.messageWarning(res.data.msg);
        }
      })
    }
    if(!this.isShareNote || this.note.editable){
      window.addEventListener('keydown', this.keydownSaveNote);
    }
    //从分享页跳转且不属于登录页 获取当前笔记
    this.note = this.$currentNote;
    this.note?.content ? this.editorData = this.note.content : this.editorData;

  },
  beforeUnmount() {
    window.removeEventListener('keydown', this.keydownSaveNote);
  },
}
</script>

<style lang="less">
#note-editor-container {
  width: 100%;
  height: 100%;
  padding: 20px;
  display: flex;
  flex-direction: column;

  #note-editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding:0 9px;
    width: 100%;
    border-radius: 10px;
    margin-bottom: 20px;
    background: rgba(255,255,255,0.5);

    .note-title{
      width: calc(100% - 220px);
      height: 80px;
      font-size: 36px;
      font-weight: bolder;
      background: rgba(255,255,255,0.2);
    }

    .functional-area{
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 240px;
      height: 80px;
      img{
        width: 30px;
        height: 30px;
        cursor: pointer;
      }
    }
  }

  #note-editor-content {
    background: #fff;
    width: 100%;
    height: calc(100% - 150px);

    .ck-editor{
      height: 100%;
      .ck-editor__main{
        height: 100%;
        .ck-content{
          height: 100%;
        }
      }
    }
  }
  //选择分类对话框
  .el-dialog{
    border-radius: 10px;
    //.el-dialog__title{
    //  font-size: 20px;
    //  letter-spacing: .1em;
    //  font-weight: bolder;
    //}
    .el-dialog__body{
      padding: 25px 25px 5px;
    }
    .el-form{
      position: relative;

      .el-form-item{
        label{
          font-size: 18px;
        }
        .el-select{
          width: 100%;
          min-width: 200px;
          margin-bottom: 10px;
        }
        .new-category-box{
          display: flex;
          width: 100%;
          justify-content: flex-end;
          align-items: center;
        }
      }
      .share-box{
        display: flex;
        flex-direction: column;
        .el-form-item__content{
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          align-items: flex-end;
          //gap: 10px;
          .el-input{
            //width: 70%;
            margin-bottom: 10px;
          }
          .el-button{
            background: #409EFF;
            width: 25%;
            font-size: 18px;
            color: #FFFFFF;
          }
        }
      }
    }
    .dialog-footer{
      .el-button{
        border-radius: 8px;
        width: 40%;
        &:first-child{
          margin-right: 20px;
        }
      }
    }
  }

  .inner-dialog{
    border-radius: 10px;
    .el-dialog{
      border-radius: 10px;
      .el-dialog__title{
        font-size: 20px;
        letter-spacing: .1em;
        font-weight: bolder;
      }
      .el-form{
        .el-form-item{
          label{
            font-size: 18px;
          }
          .el-input{
            width: 100%;
            min-width: 200px;
          }
        }
      }
    }
  }
}


</style>
